package com.gzs.learn.springcloud.demo;

import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.List;

@Getter
@RequiredArgsConstructor
public class ThreadCallableDemo {

//    public static void main(String[] args) throws InterruptedException {
//        List<Integer> list = Lists.newArrayList(1, 2, 3, 56, 7);
//        runCustomRunable(list);
//        runCustomThread(list);
//
//        // throw NPE
//        runCustomRunable(null);
//        runCustomThread(null);
//    }

    public static void runCustomRunable(List<Integer> list) throws InterruptedException {
        CustomRunable run = new CustomRunable(list);
        Thread t = new Thread(run);
        t.start();
        t.join();
        System.out.println(run.getResult());
    }

    public static void runCustomThread(List<Integer> list) throws InterruptedException {
        CustomThread run = new CustomThread(list);
        run.start();
        run.join();
        System.out.println(run.getResult());
    }

}

@RequiredArgsConstructor
@Getter
class CustomRunable implements Runnable {
    private Object result;
    private final List<Integer> numbers;

    @Override
    public void run() {
        if (numbers == null) {
            throw new NullPointerException();
        }
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        this.result = sum;
    }
}

@RequiredArgsConstructor
@Getter
class CustomThread extends Thread {
    private Object result;
    private final List<Integer> numbers;

    @Override
    public void run() {
        if (numbers == null) {
            throw new NullPointerException();
        }
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        this.result = sum;
    }
}
